public class test01 {
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
        HashMap<Integer,Integer> map;
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            map = new HashMap<>();
            for(int i = 0;i<inorder.length;i++){
                map.put(inorder[i],i);
            }
            return buildRoot(preorder,0,preorder.length,inorder,0,inorder.length);
        }
        private TreeNode buildRoot(int[]preorder,int preBegin,int preEnd,int[] inorder,int inBegin,int inEnd){
            if(preBegin>=preEnd || inBegin>=inEnd){
                return null;
            }
            int index = map.get(preorder[preBegin]);
            TreeNode root = new TreeNode(inorder[index]);
            int lenOfLeft = index-inBegin;
            root.left = buildRoot(preorder,preBegin+1,preBegin+1+lenOfLeft,inorder,inBegin,index);
            root.right = buildRoot(preorder,preBegin+1+lenOfLeft,preEnd,inorder,index+1,inEnd);
            return root;
        }
}
